<?php

class Activity_Api_Comment
{

	function remove($comment)
	{
		$resource = $comment -> getResource();
		if ($resource)
		{
			if (isset($resource -> comment_count))
			{
				$resource -> comment_count -= 1;
				$resource -> save();
			}
		}
		$comment -> delete();
		return TRUE;
	}

	/**
	 * @param Database_Model_Item $object
	 * @param int $userId
	 * @param string $body
	 * @return TRUE/FALSE
	 */
	function addComment($resource, $poster, $body)
	{
		if ($resource -> getType() == 'activity-feed')
		{
			$resource = $resource -> getObject();
		}

		$table = Nuo::getTable('activity/comment');

		$comment = $table -> fetchNew();

		$comment -> resource_id = $resource -> getItemId();

		$comment -> poster_id = $poster -> getItemId();

		$comment -> body = (string)$body;

		$comment -> created_at = time();

		$comment -> save();

		if (isset($resource -> comment_count))
		{
			$resource -> comment_count = $resource -> comment_count + 1;
			$resource -> save();
		}

		return $comment;
	}

	/**
	 * @param Database_Model_Item $resource
	 * @param int $limit
	 * @return TRUE/FALSE
	 */
	function getComments($resource, $limit = 5)
	{
		$table = Nuo::getTable('activity/comment');

		$select = $table -> select();
		$select -> where('resource_id=?', $resource -> getItemId());
		$select -> order('comment_id DESC');
		$select -> limit((int)$limit);

		$ret = array();

		$arrId = array();

		foreach ($table -> fetchAll($select) as $resource)
		{
			$arrId[] = $id = $resource -> getItemId();
			$ret[$id] = $resource;
		}

		$poster = Nuo::getUser();

		$posterId = NULL;

		if ($poster)
		{
			$posterId = Nuo::getUser() -> getItemId();
		}

		/**
		 *  fetch like
		 */

		if ($arrId && $posterId)
		{
			$table = Nuo::getTable('activity/like');
			$select = $table -> select();
			$select -> where('poster_id=?', $posterId);
			$select -> where('resource_id IN (?)', $arrId);

			foreach ($table->fetchAll($select) as $resource)
			{
				$id = $resource -> object_id;
				if (isset($ret[$id]))
				{
					$obj = $ret[$id];
					$obj -> setLiked(1);
				}
			}
		}
		return array_reverse($ret);
	}

}
